import { reqCartList, reqDeleteCartById, reqUpdateCheckedByid } from "@/api"
const actions = {
    // 获取购物车列表数据
    async getCartList({ commit }) {
        let result = await reqCartList();
        // console.log("reqCartList:", result);
        if (result.code == 200) {
            commit("GETCARTLIST", result.data)
        }
    },
    // 删除购物车某一个产品
    async deleteCartListBySkuId({ commit }, skuid) {
        let result = await reqDeleteCartById(skuid);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    // 修改购物车某一个选中
    async updateCheckedByid({ commit }, { skuId, isChecked }) {
        let a = await reqUpdateCheckedByid(skuId, isChecked);
        if (a.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    // 删除全部选中的产品
    deleteAllCheckedCart({ dispatch, getters }) {
        let PromiseAll = [];
        getters.cartList.cartInfoList.forEach(item => {
            if (item.isChecked == '1') {
                let Promise = dispatch('deleteCartListBySkuId', item.skuId);
                PromiseAll.push(Promise);
            }
        });
        return Promise.all(PromiseAll);
    },
    // 修改全部勾选状态
    updateAllCartIsChecked({ dispatch, state }, isChecked) {
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('updateCheckedByid', { skuId: item.skuId, isChecked: isChecked })
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll);
    }
};
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList;
    }
};
const state = {
    cartList: []
};
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    },
    // 计算出来的购物车数据
    cartInfoList(state) {
        return state.cartList[0].cartInfoList || []
    }
};

export default {
    actions,
    mutations,
    state,
    getters
}